#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import sys

# 读取两个文件（相对于项目根目录）
with open('../output/LAG_3_output_chunjinggang.json', 'r', encoding='utf-8') as f:
    chujinggang = json.load(f)

with open('../output/LAG_3_output.json', 'r', encoding='utf-8') as f:
    lag3 = json.load(f)

qSim_cjg = chujinggang['qSim']
timeSeries_lag3 = lag3['timeSeries']

print("=" * 120)
print("LAG_3 模型输出对比")
print("=" * 120)
print(f"初境港输出时段数: {len(qSim_cjg)}")
print(f"LAG_3 输出时段数: {len(timeSeries_lag3)}")
print()

# 对比 QSim (总流量)
print("=" * 120)
print("QSim (总流量) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'QSim(初境港)':<20} {'QSim(LAG_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

qsim_match_count = 0
qsim_total = min(30, len(qSim_cjg), len(timeSeries_lag3))

for i in range(qsim_total):
    qs_cjg = qSim_cjg[i]
    qs_lag3 = timeSeries_lag3[i]['QSim']
    time_lag3 = timeSeries_lag3[i]['time']
    is_warmup = timeSeries_lag3[i].get('isWarmUp', False)
    
    diff = abs(qs_cjg - qs_lag3)
    is_match = diff < 1e-6
    
    if is_match:
        qsim_match_count += 1
    
    warmup_mark = " [WarmUp]" if is_warmup else ""
    match_mark = "✓" if is_match else "✗"
    
    print(f"{i:<6} {time_lag3:<20} {qs_cjg:<20.6f} {qs_lag3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")

print(f"\nQSim 一致性: {qsim_match_count}/{qsim_total} ({qsim_match_count*100/qsim_total:.1f}%)")

# 对比 QS (地表径流流量)
print("\n" + "=" * 120)
print("QS (地表径流流量) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'QS(初境港)':<20} {'QS(LAG_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

# 检查 rSim 结构
if 'rSim' in chujinggang and isinstance(chujinggang['rSim'], list) and len(chujinggang['rSim']) > 0:
    # rSim[0] 是地表径流流量序列
    if isinstance(chujinggang['rSim'][0], list):
        qs_cjg_array = chujinggang['rSim'][0]
    else:
        # 如果不是嵌套列表，则整个 rSim 可能就是一个流量序列
        qs_cjg_array = chujinggang.get('rSim', [])
    
    qs_match_count = 0
    qs_total = min(30, len(qs_cjg_array), len(timeSeries_lag3))
    
    for i in range(qs_total):
        qs_cjg = qs_cjg_array[i] if i < len(qs_cjg_array) else 0.0
        qs_lag3 = timeSeries_lag3[i].get('QS', 0.0)
        time_lag3 = timeSeries_lag3[i]['time']
        is_warmup = timeSeries_lag3[i].get('isWarmUp', False)
        
        diff = abs(qs_cjg - qs_lag3)
        is_match = diff < 1e-6
        
        if is_match:
            qs_match_count += 1
        
        warmup_mark = " [WarmUp]" if is_warmup else ""
        match_mark = "✓" if is_match else "✗"
        
        print(f"{i:<6} {time_lag3:<20} {qs_cjg:<20.6f} {qs_lag3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")
    
    print(f"\nQS 一致性: {qs_match_count}/{qs_total} ({qs_match_count*100/qs_total:.1f}%)")
else:
    print("初境港输出中未找到 rSim 数据")

# 对比 QI (壤中流流量)
print("\n" + "=" * 120)
print("QI (壤中流流量) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'QI(初境港)':<20} {'QI(LAG_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

if 'rSim' in chujinggang and isinstance(chujinggang['rSim'], list) and len(chujinggang['rSim']) > 1:
    if isinstance(chujinggang['rSim'][1], list):
        qi_cjg_array = chujinggang['rSim'][1]
    else:
        qi_cjg_array = []
    
    qi_match_count = 0
    qi_total = min(30, len(qi_cjg_array), len(timeSeries_lag3))
    
    for i in range(qi_total):
        qi_cjg = qi_cjg_array[i] if i < len(qi_cjg_array) else 0.0
        qi_lag3 = timeSeries_lag3[i].get('QI', 0.0)
        time_lag3 = timeSeries_lag3[i]['time']
        is_warmup = timeSeries_lag3[i].get('isWarmUp', False)
        
        diff = abs(qi_cjg - qi_lag3)
        is_match = diff < 1e-6
        
        if is_match:
            qi_match_count += 1
        
        warmup_mark = " [WarmUp]" if is_warmup else ""
        match_mark = "✓" if is_match else "✗"
        
        print(f"{i:<6} {time_lag3:<20} {qi_cjg:<20.6f} {qi_lag3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")
    
    print(f"\nQI 一致性: {qi_match_count}/{qi_total} ({qi_match_count*100/qi_total:.1f}%)")

# 对比 QG (地下水流量)
print("\n" + "=" * 120)
print("QG (地下水流量) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'QG(初境港)':<20} {'QG(LAG_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

if 'rSim' in chujinggang and isinstance(chujinggang['rSim'], list) and len(chujinggang['rSim']) > 2:
    if isinstance(chujinggang['rSim'][2], list):
        qg_cjg_array = chujinggang['rSim'][2]
    else:
        qg_cjg_array = []
    
    qg_match_count = 0
    qg_total = min(30, len(qg_cjg_array), len(timeSeries_lag3))
    
    for i in range(qg_total):
        qg_cjg = qg_cjg_array[i] if i < len(qg_cjg_array) else 0.0
        qg_lag3 = timeSeries_lag3[i].get('QG', 0.0)
        time_lag3 = timeSeries_lag3[i]['time']
        is_warmup = timeSeries_lag3[i].get('isWarmUp', False)
        
        diff = abs(qg_cjg - qg_lag3)
        is_match = diff < 1e-6
        
        if is_match:
            qg_match_count += 1
        
        warmup_mark = " [WarmUp]" if is_warmup else ""
        match_mark = "✓" if is_match else "✗"
        
        print(f"{i:<6} {time_lag3:<20} {qg_cjg:<20.6f} {qg_lag3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")
    
    print(f"\nQG 一致性: {qg_match_count}/{qg_total} ({qg_match_count*100/qg_total:.1f}%)")

# 全部时段统计
print("\n" + "=" * 120)
print("全部时段统计")
print("=" * 120)

total_len = min(len(qSim_cjg), len(timeSeries_lag3))
qsim_all_match = sum(1 for i in range(total_len) if abs(qSim_cjg[i] - timeSeries_lag3[i]['QSim']) < 1e-6)

# 统计三水源分量
qs_all_match = 0
qi_all_match = 0
qg_all_match = 0

if 'rSim' in chujinggang and isinstance(chujinggang['rSim'], list):
    if len(chujinggang['rSim']) > 0 and isinstance(chujinggang['rSim'][0], list):
        qs_all_match = sum(1 for i in range(min(total_len, len(chujinggang['rSim'][0]))) 
                          if abs(chujinggang['rSim'][0][i] - timeSeries_lag3[i].get('QS', 0.0)) < 1e-6)
    
    if len(chujinggang['rSim']) > 1 and isinstance(chujinggang['rSim'][1], list):
        qi_all_match = sum(1 for i in range(min(total_len, len(chujinggang['rSim'][1]))) 
                          if abs(chujinggang['rSim'][1][i] - timeSeries_lag3[i].get('QI', 0.0)) < 1e-6)
    
    if len(chujinggang['rSim']) > 2 and isinstance(chujinggang['rSim'][2], list):
        qg_all_match = sum(1 for i in range(min(total_len, len(chujinggang['rSim'][2]))) 
                          if abs(chujinggang['rSim'][2][i] - timeSeries_lag3[i].get('QG', 0.0)) < 1e-6)

print(f"总时段数: {total_len}")
print(f"QSim (总流量) 完全一致的时段数: {qsim_all_match}/{total_len} ({qsim_all_match*100/total_len:.1f}%)")
if qs_all_match > 0:
    print(f"QS (地表径流流量) 完全一致的时段数: {qs_all_match}/{total_len} ({qs_all_match*100/total_len:.1f}%)")
if qi_all_match > 0:
    print(f"QI (壤中流流量) 完全一致的时段数: {qi_all_match}/{total_len} ({qi_all_match*100/total_len:.1f}%)")
if qg_all_match > 0:
    print(f"QG (地下水流量) 完全一致的时段数: {qg_all_match}/{total_len} ({qg_all_match*100/total_len:.1f}%)")

# 总体结论
print("\n" + "=" * 120)
print("总体结论")
print("=" * 120)

if qsim_all_match == total_len:
    print("✓✓✓ 两个模型输出**完全一致**！")
    sys.exit(0)
elif qsim_all_match >= total_len * 0.95:
    print("⚠ 两个模型输出基本一致，但存在少量差异")
    sys.exit(0)
else:
    print("✗✗✗ 两个模型输出存在显著差异，需要进一步检查")
    
    # 找出第一个不匹配的时段
    first_diff_qsim = next((i for i in range(total_len) if abs(qSim_cjg[i] - timeSeries_lag3[i]['QSim']) >= 1e-6), -1)
    
    if first_diff_qsim >= 0:
        print(f"\n第一个 QSim 不匹配出现在索引 {first_diff_qsim}")
        print(f"  时间: {timeSeries_lag3[first_diff_qsim]['time']}")
        print(f"  初境港: {qSim_cjg[first_diff_qsim]:.10f}")
        print(f"  LAG_3:  {timeSeries_lag3[first_diff_qsim]['QSim']:.10f}")
        print(f"  差值:   {abs(qSim_cjg[first_diff_qsim] - timeSeries_lag3[first_diff_qsim]['QSim']):.10f}")
    
    sys.exit(1)

